package com.ruicar.afs.cloud.batch.frame.logger;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.batch.enums.MessageType;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * The type WsMonitorHelper
 * <p>Description: </p>
 * 每天打开监控的人不多所以用此方案处理
 * @author Fzero
 * @version 1.0
 * @date Created on 2020.08.08 13:22:45
 * @since 1.0
 */
public class WsMonitorHelper {
    /**
     * Session list
     * <p>Description: </p>
     */
    private static Map<String,Session> sessionList = new HashMap<>();


    public static void addSession(Session session){
        sessionList.put(session.getId(),session);
    }


    public static void removeSession(Session session){
        sessionList.remove(session.getId());
    }

    /**
     * Send message *
     *
     * @param message message
     */
    public static void sendMessage(MessageType type, String message){
        String timeStamp = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATETIME_MS_PATTERN);
        ThreadUtil.execute(()->{
            sessionList
                    .values()
                    .stream()
                    .forEach(session -> {
                        try {
                            if(!session.isOpen()) return;
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", AfsEnumUtil.key(type));
                            jsonObject.put("timeStamp",timeStamp);
                            jsonObject.put("message",message);
                            jsonObject.put("uuid", UUID.randomUUID().toString().replaceAll("-",""));
                            session.getBasicRemote().sendText(jsonObject.toJSONString());
                        } catch (Throwable e) {
                            LoggerFactory.getLogger("batch-control").error("",e);
                        }
                    });
        });
    }
}
